
### PackageManager Description Start ###
# 1,配合ChangeLog使用.
# 2,编译和打包.
# 3,检查当前主工程的版本号.
# 4,编译打包到蒲公英
### PackageManager Description End  ###


### Input Start ###
# 所有的需要用户配置的信息
# 工程的info.plist文件路径
projectInfoPlistPath="/Users/gikkiares/Desktop/PP_PersonalProject/MP01_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/01_JsoUtilitySdkDemoProject/05_Make/JsoUtilitySdkDemo/JsoUtilitySdkDemo/JsoUtilitySdkDemo/Info.plist"
workspaceFilePath="/Users/gikkiares/Desktop/PP_PersonalProject/MP01_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/01_JsoUtilitySdkDemoProject/05_Make/JsoUtilitySdkDemo/JsoUtilitySdkDemo/JsoUtilitySdkDemo.xcworkspace"
pgyApiKey="d547a764af6e143b8021d29ec8f83c7f"
# changeLog文件路径.
changeLogPath="/Users/gikkiares/Desktop/PP_PersonalProject/MP01_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/01_JsoUtilitySdkDemoProject/05_Make/JsoUtilitySdkDemo/JsoUtilitySdkDemo/ReadMe/ChangeLog.md"
projectDirPath="/Users/gikkiares/Desktop/MP_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/JsUtilityDemo/JsUtilityDemo"

configuration="Release"
scheme="JsoUtilitySdkDemo"
targetName="JsoUtilitySdkDemo"


teamId="726NDCHRGU"
bundleId="com.vgemv.JsoUtilitySdkDemo"
### Input End  ###


### Variable Start ### 
#程序需要用到的变量
# Change log中指定的版本.
newVersion=""
newBuildNumber=""
# 改动点.
change=""
# plist文件中指定的版本
currentVersion=""
currentBuildNumber=""

# 上传结果
uploadResult=""

buildDir=""
g_outArchivePath=""
# 输出文件的目录
exportDirPath=""
g_exportPlistFilePath="/Users/gikkiares/Desktop/PP_PersonalProject/MP01_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/01_JsoUtilitySdkDemoProject/05_Make/JsoUtilitySdkDemo/PackageScript/ExportOptions.plist"
ipaPath=""

### Variable End ###


function main {

    # 1 获取工程当前版本
    currentVersion=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "${projectInfoPlistPath}")
	[[ $? != 0 ]] && echo "Get current version failed!" && exit 
    buildNumberForVersion ${currentVersion}
    currentBuildNumber=$?
    echo "Current version is: ${currentVersion},build number is: ${currentBuildNumber}"

    # 2 获取工程最新版本
    ### 1.1.1 获取Version
    newVersion=$(awk 'BEGIN {currentTagIndex=0;version=""} {if($1 == "#"){currentTagIndex++; if(currentTagIndex==1){version=""$2;version2=substr(version,2,length(version)-2) ;exit}}} END{print version2}' ${changeLogPath})
	[[ $? != 0 ]] && echo "Get new version failed!" && exit 

    buildNumberForVersion ${newVersion}
    newBuildNumber=$?
    echo "New version is: ${newVersion},build number is: ${newBuildNumber}"

  
    ## 1.3 比较,如果相同则
    if (( ${newBuildNumber} >= ${currentBuildNumber} )); then

		  ### 1.1.2 获取change
    	change=$(awk 'BEGIN {currentTagIndex=0;comment="";} {if($1 == "#"){currentTagIndex++;}  if(currentTagIndex == 1) {comment = (comment""$0"\n")}else if(currentTagIndex>1){exit} } END{print comment}' ${changeLogPath})
    	echo "New version change is :\n${change}\n"

        echo "Do you want to upgrade version from ${currentVersion} to ${version} Y/n?"
        read choice
        if [[ "${choice}" != "n" ]]; then
            # build目录
            buildDir="${workspaceFilePath}/../../Build"
            buildDir_newVersion="${buildDir}/${newVersion}"
            # 归档文件
            g_outArchivePath="${buildDir_newVersion}/${targetName}.xcarchive"
            # 导出文件目录
            exportDirPath="${buildDir_newVersion}/export"
            ipaPath="${exportDirPath}/${targetName}.ipa"
			
            upgradeVersion ${newVersion}
            archive
            exportIpa 
			echo "Do you want to upload ipa to pgy? y/n"
			read choice 
			if [[ "${choice}" == "y" ]]; then
            	uploadIpaToPgy
            	parseUploadResult
            	echo "All done."
			else 
				echo "All done."
			fi
        else
            exit
        fi
    else
        echo "New version is not above current version."
        exit
    fi
}

function buildNumberForVersion {
    version=$1
    array=(${version//./ })  
    # echo ${array[0]};
    # echo ${array[@]}
    declare -i i=2
    declare -i buildNumber=0
    for var in ${array[@]}
    do
        ((buildNumber += ${var} * 100 ** i)) 
        ((--i))
    done
    # echo "BuildNumber is: ${buildNumber}"
    return ${buildNumber}
}

## 1.4 设置xcode版本
function upgradeVersion {
   setProjectVersion ${newVersion}
}

function setProjectVersion {
	version=$1
	echo "Version is ${version}"

	version=${newVersion}
	buildNumberForVersion ${version}
    buildNumber=$?

    #  shortVersion为指定的版本号eg: 1.2.3
    /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${version}" "${projectInfoPlistPath}"
    # 设置build号.
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${buildNumber}" "${projectInfoPlistPath}"

    # cd ${projectDirPath}
    # #更新所有Target的${MARKETING_VERSION},用于设置short version
    # xcrun agvtool new-marketing-version ${version}
    # #更新${CURRENT_PROJECT_VERSION}用于设置build number
    # xcrun agvtool new-version ${buildNumber}
}

function rollbackVersion {
	setProjectVersion ${currentVersion}
}

# 项目编译并打包为.xcarchive文件.
function archive {
    # xcodebuild -project Pods/Pods.xcodeproj build
    echo "+++ Compile project start +++"
    if [[ ! -e "${g_outArchivePath}" ]]; then
        xcodebuild -archivePath ${g_outArchivePath} -workspace ${workspaceFilePath} -sdk iphoneos -scheme ${scheme} -configuration ${configuration} archive
		[[ $? != 0 ]] && echo "export ipa failed" && rollbackVersion && exit
    else 
        echo "xcarchive file exists."
    fi
    echo "=== Compile project finish ==="
}

# 将app签名=>ipa
function exportIpa() {
    echo "+++ Export ipa start +++"
    if [[ ! -e "${exportDirPath}" ]]; then
        xcodebuild -exportArchive -archivePath "${g_outArchivePath}"  -exportPath "${exportDirPath}" -exportOptionsPlist ${g_exportPlistFilePath}
    else 
        echo " "
    fi
    echo "=== Export ipa fiish ==="
}

function uploadIpaToPgy {
    echo "+++ Upload to pgy start +++"
       if [[ -e "${ipaPath}" ]]; then
       echo "ipa file exists."
        uploadResult=`curl -F "file=@${ipaPath}" -F "_api_key=${pgyApiKey}" -F "buildUpdateDescription=${change}" 'http://www.pgyer.com/apiv2/app/upload'`
		[[ $? != 0 ]] && echo "upload ipa to pgy failed" && rollbackVersion && exit 
    else
        echo "ipa包不存在."
    fi
    echo "=== Upload to pgy finish ==="
}

function parseUploadResult {
        echo "result is ${uploadResult}"
        buildKey=`echo ${uploadResult} | tr '\r\n' ' ' | jq '.data.buildKey'`
        echo "buildKey is ${buildKey}"
        appDownloadUrl="https://www.pgyer.com/${buildKey}"
        echo ${appDownloadUrl} | xargs open -a "/Applications/Google Chrome.app"
}



main
